package com.linjinp.study.算法;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 水仙花数，找出各位数的3次方之和等于本身的树
 * @Author: linjinp
 * @Date: 2021/6/3 9:32
 */
public class DaffodilNum extends RecursiveTask<String> {

    // 数组
    private int[] src;
    // 开始索引
    private int beginInedx;
    // 结束索引
    private int endInedx;

    public DaffodilNum(int[] src, int beginInedx, int endInedx) {
        this.src = src;
        this.beginInedx = beginInedx;
        this.endInedx = endInedx;
    }

    @Override
    protected String compute() {
        if (endInedx == beginInedx) {
            int num = src[beginInedx];
            if (num >= 100 && num <= 999) {
                int a = num / 100;
                int b = num % 100 / 10;
                int c = num % 100 % 10;
                if (a*a*a + b*b*b + c*c*c == num) {
                    return String.valueOf(num);
                }
            }
            return null;
        } else {
            // 继续从中间进行切分
            int mid = (beginInedx + endInedx) / 2;
            // 切分出左右两个分片
            DaffodilNum left = new DaffodilNum(src, beginInedx, mid);
            DaffodilNum right = new DaffodilNum(src, mid + 1, endInedx);
            invokeAll(left, right);
            return mergetString(left.join(), right.join());
        }
    }

    /**
     * 字符串合并
     * @param str1
     * @param str2
     * @return
     */
    private static String mergetString(String str1, String str2) {
        if (str1 != null && str2 != null) {
            return str1 + "，" + str2;
        }
        if (str1 != null) {
            return str1;
        }
        if (str2 != null) {
            return str2;
        }
        return null;
    }

    private static int[] createData() {
        int[] src = new int[900];
        int index = 0;
        for (int i = 100; i <= 999 ; i++) {
            src[index] = i;
            index++;
        }
        return src;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        int[] src = createData();
        DaffodilNum sort = new DaffodilNum(src, 0, src.length - 1);
        pool.invoke(sort);
        String result = sort.join();
        System.out.println("水仙花数：" + result);
    }

}
